package org.cloudlab.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cloudlab.bean.SysUser;
import org.cloudlab.common.CommonConst;
import org.cloudlab.common.RemoveState;
import org.cloudlab.mapper.AcademicJournalMapper;
import org.cloudlab.bean.AcademicJournal;
import org.cloudlab.service.IAcademicJournalService;
import org.cloudlab.service.ISubRecordService;
import org.cloudlab.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 期刊服务层实现
 *
 * @author Liu Yicong
 * @date 2023/9/3
 */
@Service
public class AcademicJournalServiceImpl
		extends ServiceImpl<AcademicJournalMapper, AcademicJournal> implements IAcademicJournalService {

	@Autowired
	private AcademicJournalMapper journalMapper;

	@Autowired
	private JwtTokenUtil tokenUtil;

	@Autowired
	@Lazy
	private ISubRecordService subRecordService;

	/**
	 * 分页查询
	 *
	 * @param page    分页信息
	 * @param journal 查询条件
	 * @return 期刊的分页
	 */
	@Override
	public Page<AcademicJournal> queryByPage(Page<AcademicJournal> page, AcademicJournal journal, String sortOrder) {
		long start = page.getCurrent();
		long size = page.getSize();
		List<AcademicJournal> result = journalMapper.queryByPage((start - 1) * size, size, journal, sortOrder);
		Long count = journalMapper.queryPageCount(journal);
		page.setTotal(count);
		page.setRecords(result);
		return page;
	}

	@Override
	@Transactional(rollbackFor = RuntimeException.class)
	public void delete(Long journalId) {
		SysUser currentUser = tokenUtil.getCurrentUser();
		Long userId = currentUser.getId();
		AcademicJournal journal = this.getById(journalId);
		if (!Objects.equals(userId, CommonConst.ADMIN_ID)) {
			throw new RuntimeException("你没有更新期刊信息的权限哦, 如果需要删除, 请使用管理员账户");
		}
		subRecordService.deleteBatchByJournalId(journalId);

		journal.setIsRemove(RemoveState.REMOVED.getValue());
		journal.setUpdateUserId(userId);
		journal.setUpdateTime(new Date());
		this.updateById(journal);
	}

	@Override
	public void add(AcademicJournal journal) {
		SysUser currentUser = tokenUtil.getCurrentUser();
		journal.setCreateUserId(currentUser.getId());
		// 查询是否有重名的, 避免重复添加
		// 去掉两边的空格
		String journalName = journal.getJournalName().trim();

		List<AcademicJournal> list = this.lambdaQuery()
				.eq(AcademicJournal::getIsRemove, RemoveState.NOT_REMOVE.getValue())
				.apply("LOWER(journal_name) = {0}", journalName)
				.list();

		// 存在同名的情况
		if (!list.isEmpty()) {
			throw new RuntimeException("添加失败, 看看是否存在期刊名相同的期刊吧");
		}

		journal.setJournalName(journalName);
		journal.setCreateTime(new Date());
		this.save(journal);
	}
}
